package com.hr.异步调用;

import lombok.SneakyThrows;



/**
 * @program: leetcode
 * @description: 公平
 * @author: HuRan QQ1345122890
 * @create: 2021-08-17 10:46
 */
public class ReentrantLockTest02 {
    public static void main(String[] args) {
        WaitNotify waitNotify = new WaitNotify(1, 5);
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                waitNotify.print("a", 1, 2);
            }
        }).start();
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                waitNotify.print("b", 2, 3);
            }
        }).start();
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                waitNotify.print("c", 3, 1);
            }
        }).start();
    }
}

class WaitNotify {
    private int flag;
    private int count;

    public void print(String str, int waitFlag, int nextFlag) throws InterruptedException {
        for (int i = 0; i < count; i++) {
            synchronized (this) {
                while (flag != waitFlag) {
                    this.wait();
                }
                System.out.println(str);
                flag = nextFlag;
                this.notifyAll();
            }
        }
    }

    public WaitNotify(int flag, int count) {
        this.flag = flag;
        this.count = count;
    }
}